#include "BackSvr.h"
#include "proto_package.h"
#include "CmdId.h"
#include "proto_msg_handler.h"
CBackSvr::CBackSvr(uv_loop_t* loop) : m_timer(loop)
{
	m_clientPtr = CTCPClient::NewTCPClien(loop);
	CMsgHandler* hlr = new CBackSvrMsgHandler;
	m_msgHlrPtr = CMsgHandlerPtr(hlr);
}


CBackSvr::~CBackSvr()
{
	LOG_INFO("~CBackSvr()");
	m_clientPtr=nullptr;
}
void CBackSvr::StopSvr()
{
	m_clientPtr->CloseConn();
	m_timer.StopTimer();
}

void CBackSvr::StartRegister(std::string ip, uint16_t port)
{
	
	m_clientPtr->OnConnStatus([=](CTCPClientPtr clt, int status){
		if (status == 0)
		{
			SBuf msg;
			CProtoPackage::PackBackSvrRegisterMsg(m_moduleid, &msg);
			clt->Write(msg.data(), msg.len());

			m_timer.StartTimer(0, 15 * 1000, [](void* usrData){
				CTCPClientPtr* cltPtr=((CTCPClientPtr*)usrData);
				SBuf msg;
				CProtoPackage::PackHeartbeatReqMsg(&msg);
				(*cltPtr)->Write(msg.data(), msg.len());
			}, (void*)(&m_clientPtr));

			clt->OnMsgCall([=](SessionPtr session, char* szByte, int len){
				m_msgHlrPtr->HandleMsg(session, szByte, len);
			});
			clt->OnClose([=](SessionPtr session) {	
				printf("client close\n");				
			});						
		}		
	});
	m_clientPtr->SetReConnInteral(5 * 1000);
	m_clientPtr->Connect((char*)ip.c_str(), port);
}